package com.piesat.quake.business.device.mqtt.param;

import com.piesat.quake.business.device.mqtt.convert.Convert;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;

import io.netty.buffer.ByteBuf;

public class ConvertParseParam extends ParseParam implements Convert {

    private Convert convert;
    private final int length;

    public ConvertParseParam(Field field, Class<? extends Convert> clazz,int length) {
        super(field, -1);
        this.length = length;
        initConverter(clazz);
    }

    private void initConverter(Class<? extends Convert> clazz) {
        try {
            this.convert = clazz.getConstructor().newInstance();
        } catch (InstantiationException | IllegalAccessException | InvocationTargetException | NoSuchMethodException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public int getLength() {
        return length;
    }

    @Override
    public Object read(ByteBuf byteBuf,ParseParam param) {
        return convert.read(byteBuf,param);
    }

    @Override
    public void write(ByteBuf byteBuf, Object value,ParseParam param) {
        convert.write(byteBuf, value,param);
    }

    @Override
    public String toString() {
        return "ConvertParseParam{" +
                "convert=" + convert +
                ", length=" + length +
                ", field=" + field +
                ", type=" + type +
                '}';
    }
}